import { ref } from 'vue';
import { fileUploadAPI } from "@/api/fileUpload.js";
import { ElMessage } from 'element-plus';

export function useFileSelect() {
  const selectedFile = ref(null);
  const accept = ref('.jpg,.png,.jpeg')
  const fileType = ref(1)

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    const fileType = file.type.split('/')[1]
    console.log(fileType, accept.value)
    // 验证格式
    if (file && accept.value) {
      if (!accept.value.includes(fileType)) {
        ElMessage.error('请上传图片文件')
        return
      }
    }
    if (file) {
      selectedFile.value = file
    }
  }

  const triggerFileSelect = (e, acceptType = '', fType = 1) => {
    fileType.value = fType
    if (acceptType) {
      accept.value = acceptType
    } else {
      accept.value = '.jpg,.png,.jpeg'
    }
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = acceptType || accept.value;
    fileInput.multiple = false
    fileInput.onchange = handleFileChange;
    fileInput.click();
  }

  // 上传文件
  const uploadFile = async (File = null) => {
    const formData = new FormData();
    if (File) {
      formData.append('file', File)
    } else {
      formData.append('file', selectedFile.value)
    }
    return await fileUploadAPI(formData)
  }

  return {
    fileType,
    selectedFile,
    triggerFileSelect,
    uploadFile
  }
}